import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '../store'
import { getToken } from '../utils/auth'
import { errors } from '../api/error'
import packageConfig from '../../package.json'
import { getClientInfo } from './client_info'
import { getBaseUrl } from './baseUrl'
import _validate from '../framework/commonJs/wptx_validate'
import { Loading } from 'element-ui'

const service = axios.create({
  baseURL: getBaseUrl(),
  timeout: 60000
})
var isLoading = true
var loadingInstance
service.defaults.headers.post['Content-Type'] = 'application/json'

service.interceptors.request.use(config => {
  const postType = config.method

  if (isLoading && postType != 'transpost') {
    loadingInstance = Loading.service({
      text: '加载中'
    })
  }
  if (postType == 'transpost') {
    config.method = 'post'
  }
  if (store.getters.token) {
    // config.headers['Authorization'] = JSON.stringify({ 'token': getToken() })
    config.headers['clientInfo'] = getClientInfo()
  }
  if (!_validate.checkEmpty(sessionStorage.getItem('token'))) {
    config.headers['Authorization'] = JSON.stringify({ 'token': sessionStorage.getItem('token') })
  }
  if (!_validate.checkEmpty(sessionStorage.getItem('token_crec'))) {
    config.headers['token_crec'] = sessionStorage.getItem('token_crec')
  }
  let req_model = {
    appName: packageConfig.name,
    format: '',
    sign: '',
    source: 'crec_front_web',
    timestamp: new Date().getTime() + '',
    version: packageConfig.version
  }
  switch (config.method) {
    case 'post':
      req_model.param = config.data
      config.data = req_model
      break
    case 'get':
      break
    case 'postout':
      config.method = 'post'
      req_model = config.data
      config.data = req_model
      break
  }
  return config
}, error => {
  if (isLoading && !_validate.checkEmpty(loadingInstance)) {
    loadingInstance.close()
  }
  let msg = ''
  if (error.message) {
    msg = error.message
  } else {
    msg = error.msg
  }
  Message({
    message: '请求异常 ' + msg,
    type: 'error',
    duration: 3 * 1000
  })
  return Promise.reject(error)
})

service.interceptors.response.use(response => {
  if (response.config.responseType === 'blob') {
    if (response.config.filetype === 'pdf') {
      if (isLoading && !_validate.checkEmpty(loadingInstance)) {
        loadingInstance.close()
      }
      return response.data
    } else {
      if (isLoading && !_validate.checkEmpty(loadingInstance)) {
        loadingInstance.close()
      }
      return response
    }
  }
  const res = response.data
  if (res.code === 200 || res.errorCode == 0 || res.rtn == 0) { // 订单详情  //rtn 售后订单
    if (isLoading && !_validate.checkEmpty(loadingInstance)) {
      loadingInstance.close()
    }
    return res
  }
  if (response.config.responseType === 'pdf') {
    if (isLoading && !_validate.checkEmpty(loadingInstance)) {
      loadingInstance.close()
    }
    return res
  }
  // ---待定安页面定案失败错误码-450
  if (res.code == -450) {
    if (isLoading && !_validate.checkEmpty(loadingInstance)) {
      loadingInstance.close()
    }
    Message({
      message: res.result,
      type: 'error',
      duration: 3 * 1000
    })
    return
  }
  if (res.code !== 200) {
    if (res.code == '805') {
      // 如果没有之前登录就去再登录，否则弹框提示回到登录页
      if (store.getters.token) {
        MessageBox.confirm(
          '该用户已经在其他设备登录了。请重新登录',
          '提示',
          {
            confirmButtonText: '确定',
            type: 'warning'
          }
        ).then(() => {
          // 顶号
          store.dispatch('FedLogOut').then(() => {
            location.reload()
          })
        })
      } else {
        return Promise.resolve({ again: true })
      }
    }
    if (res.code !== '-112') {
      let msg = ''
      if (res.message) {
        msg = res.message
      } else {
        msg = res.msg
      }
      Message({
        message: exception(res.code, msg),
        type: 'error',
        duration: 3 * 1000
      })
    }
    // 以下错误码处理需要强制退出登录状态的.
    // ---------------------------------------------
    if (res.code === '-2' || res.code == '804') {
      store.dispatch('FedLogOut').then(() => {
        location.reload()
      })
    }
    if (isLoading && !_validate.checkEmpty(loadingInstance)) {
      loadingInstance.close()
    }
    // ----------------------------------------------
    return Promise.reject({ e: 'error' })
  } else {
    if (isLoading && !_validate.checkEmpty(loadingInstance)) {
      loadingInstance.close()
    }
    return response.data
  }
}, error => {
  if (isLoading && !_validate.checkEmpty(loadingInstance)) {
    loadingInstance.close()
  }
  let code = ''
  if (error.response) {
    code = error.response.status
  } else {
    code = '网络已断开'
  }
  Message({
    message: '网络不给力(' + code + ')',
    type: 'error',
    duration: 3 * 1000
  })
  return Promise.reject(error)
})

function exception(code, message) {
  const list = errors.filter(e => {
    return e.code === code
  })
  if (list.length === 0) {
    return message
  } else {
    return list[0].message
  }
}

export default service
